package hashtable;

import java.util.Scanner;

public class HashTableDemo {

  public static void main(String[] args) {
    HashTable hashTable = new HashTable(7);

    String key = "";
    Scanner scanner = new Scanner(System.in);
    while(true) {
      System.out.println("add:  添加雇员");
      System.out.println("list: 显示雇员");
      System.out.println("find: 查找雇员");
      System.out.println("exit: 退出系统");

      key = scanner.next();
      switch (key) {
        case "add":
          System.out.println("输入id");
          int id = scanner.nextInt();
          System.out.println("输入名字");
          String name = scanner.next();
          //创建 雇员
          Emp emp = new Emp(id, name);
          hashTable.add(emp);
          break;
        case "list":
          hashTable.list();
          break;
        case "find":
          System.out.println("请输入要查找的id");
          id = scanner.nextInt();
          hashTable.find(id);
          break;
        case "exit":
          scanner.close();
          System.exit(0);
        default:
          break;
      }
    }
  }
}


class HashTable{
  int maxSize;
  EmpLinkedList[] empLinkedLists;

  public HashTable(int maxSize) {
    this.maxSize = maxSize;
    this.empLinkedLists = new EmpLinkedList[maxSize];
    for (int i = 0; i < maxSize; i++) {
      empLinkedLists[i] = new EmpLinkedList();
    }
  }

  //散列函数
  public int hashFun(int id){
    return id%maxSize;
  }

  //添加
  public void add(Emp emp){
    int empLinkedId = hashFun(emp.id);
    empLinkedLists[empLinkedId].add(emp);
  }

  //遍历
  public void list(){
    for (int i = 0; i < maxSize; i++) {
      empLinkedLists[i].list(i+1);
    }
  }

  //查找
  public void find(int id){
    int no = hashFun(id);
    Emp emp = empLinkedLists[no].findEmpById(id);
    if (emp==null){
      System.out.println("未找到");
    }else {
      System.out.println(emp);
    }

  }
}

class EmpLinkedList {
  private Emp head;

  // 添加
  public void add(Emp emp) {
    if (head == null) {
      head = emp;
      return;
    }
    Emp temp = head;
    while (temp.next != null) {
      temp = temp.next;
    }
    temp.next = emp;
  }

  // 遍历
  public void list(int no) {
    if (head == null) {
      System.out.println("第" + no + "链表中无元素");
      return;
    }
    Emp temp = head;
    System.out.print("第" + no + "链表中: ");
    while (temp != null) {
      System.out.print(temp);
      temp = temp.next;
    }
  }

  //查找
  public Emp findEmpById(int id) {
    if (head == null){
      return head;
    }
    Emp temp=head;
    while (temp!=null){
      if (temp.id==id){
        return temp;
      }
      temp = temp.next;
    }
    return null;
  }
}

class Emp {
  public int id;
  public String name;
  public Emp next;

  public Emp(int id, String name) {
    this.id = id;
    this.name = name;
  }

  @Override
  public String toString() {
    return "Emp{" + "id=" + id + ", name='" + name + '\'' + '}';
  }
}
